package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.entity.UpdateArticleMessage;
import com.heima.behavior.service.ReadBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ReadBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Value("${topic.read_behavior}")
    private String readBehavior;
    /**
     * 阅读行为记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult ReadBehavior(ReadBehaviorDto dto) {
        //线程拿到用户
        User user = AppThreadLocalUtil.get();

        ApReadBehavior apReadBehavior = new ApReadBehavior();
        apReadBehavior.setArticleId(dto.getArticleId());
        if (user != null){
            apReadBehavior.setUserId(user.getUserId());
        }else {
            apReadBehavior.setEquipmentId(dto.getEquipmentId());
        }
        apReadBehavior.setReadDuration(dto.getReadDuration());
        apReadBehavior.setPercentage(dto.getPercentage());
        apReadBehavior.setLoadDuration(dto.getLoadDuration());
        apReadBehavior.setCreatedTime(new Date());
        apReadBehavior.setUpdatedTime(new Date());
        //查询当前用户之前是否有阅读过此篇文章
        Query query = new Query();
        if (user == null){
            //设备登录
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior one = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (one == null){
            //没有阅读记录
            //阅读次数+1
            apReadBehavior.setCount(dto.getCount());
            mongoTemplate.save(apReadBehavior);
        }else {
            //有过阅读记录,每次阅读都要将阅读记录加1
            Update update = new Update();
            update.inc("count");
            update.set("updatedTime",new Date());
            update.set("readDuration",dto.getReadDuration());
            update.set("percentage",dto.getPercentage());
            update.set("loadDuration",dto.getLoadDuration());
            mongoTemplate.updateFirst(query,update,ApReadBehavior.class);
        }
        //Kafka发消息
        UpdateArticleMessage updateMsg = new UpdateArticleMessage();
        updateMsg.setType(0);
        updateMsg.setAdd(1);
        updateMsg.setArticleId(dto.getArticleId());
        kafkaTemplate.send(readBehavior, JSON.toJSONString(updateMsg));
        return ResponseResult.okResult();
    }
}
